/*
 *
 * Copyright (c) 2020 The Raptor Authors. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "src/surface/acceptor.h"

#include "raptor-lite/impl/config.h"
#include "raptor-lite/impl/property.h"
#ifdef _WIN32
#include "src/windows/tcp_listener.h"
#else
#include "src/linux/tcp_listener.h"
#endif
#include "src/common/resolve_address.h"

namespace raptor {

AcceptorAdaptor::AcceptorAdaptor(AcceptorHandler *handler)
    : _impl(new TcpListener(handler)) {}

AcceptorAdaptor::~AcceptorAdaptor() { delete _impl; }

#ifdef _WIN32
raptor_error AcceptorAdaptor::Init(PollingThread *p) { return _impl->Init(p); }
#else
raptor_error AcceptorAdaptor::Init() { return _impl->Init(1); }
#endif
raptor_error AcceptorAdaptor::Start() { return _impl->Start(); }

void AcceptorAdaptor::Shutdown() { _impl->Shutdown(); }

raptor_error AcceptorAdaptor::AddListening(const std::string &addr) {
    raptor_resolved_addresses *addrs = nullptr;
    raptor_error e = raptor_blocking_resolve_address(addr.c_str(), nullptr, &addrs);
    if (e == RAPTOR_ERROR_NONE) {
        for (size_t i = 0; i < addrs->naddrs; i++) {
            e = _impl->AddListeningPort(&addrs->addrs[i]);
            if (e != RAPTOR_ERROR_NONE) {
                break;
            }
        }
    }
    raptor_resolved_addresses_destroy(addrs);
    return e;
}

} // namespace raptor
